package com.socialsoftware.ui.notifications.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.socialsoftware.R;
import com.socialsoftware.adapter.CommentAdapter;
import com.socialsoftware.adapter.ImageGridAdapter;
import com.socialsoftware.model.Moment;
import com.socialsoftware.model.User;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import de.hdodenhof.circleimageview.CircleImageView;

public class MomentsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_HEADER = 0;
    private static final int TYPE_MOMENT = 1;

    private Context context;
    private List<Moment> moments;
    private OnMomentClickListener momentClickListener;
    private OnLikeClickListener likeClickListener;
    private OnCommentClickListener commentClickListener;

    public interface OnMomentClickListener {
        void onMomentClick(Moment moment);
    }

    public interface OnLikeClickListener {
        void onLikeClick(Moment moment, int position);
    }

    public interface OnCommentClickListener {
        void onCommentClick(Moment moment, int position);
    }

    public MomentsAdapter(Context context, OnMomentClickListener momentClickListener,
                          OnLikeClickListener likeClickListener, OnCommentClickListener commentClickListener) {
        this.context = context;
        this.moments = new ArrayList<>();
        this.momentClickListener = momentClickListener;
        this.likeClickListener = likeClickListener;
        this.commentClickListener = commentClickListener;
    }

    public void setMoments(List<Moment> moments) {
        this.moments = moments;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_moments_header, parent, false);
            return new HeaderViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_moment, parent, false);
            return new MomentViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeaderViewHolder) {
            bindHeaderViewHolder((HeaderViewHolder) holder);
        } else {
            bindMomentViewHolder((MomentViewHolder) holder, position - 1);
        }
    }

    private void bindHeaderViewHolder(HeaderViewHolder holder) {
        // In a real app, load user profile data
        holder.usernameTextView.setText("我的名字");
        
        // Load cover image
        Glide.with(context)
                .load("https://picsum.photos/id/1015/1200/400")
                .placeholder(R.drawable.default_cover)
                .into(holder.coverImageView);
        
        // Load avatar
        Glide.with(context)
                .load("https://randomuser.me/api/portraits/men/85.jpg")
                .placeholder(R.drawable.default_avatar)
                .into(holder.avatarImageView);
    }

    private void bindMomentViewHolder(MomentViewHolder holder, int position) {
        Moment moment = moments.get(position);
        
        // User info
        holder.usernameTextView.setText(moment.getUser().getName());
        holder.timeTextView.setText(getTimeAgo(moment.getTimestamp()));
        
        // Load avatar
        Glide.with(context)
                .load(moment.getUser().getAvatarUrl())
                .placeholder(R.drawable.default_avatar)
                .into(holder.avatarImageView);
        
        // Content
        holder.contentTextView.setText(moment.getContent());
        
        // Images
        setupImageGrid(holder, moment);
        
        // Location
        if (!TextUtils.isEmpty(moment.getLocation())) {
            holder.locationTextView.setVisibility(View.VISIBLE);
            holder.locationTextView.setText(moment.getLocation());
        } else {
            holder.locationTextView.setVisibility(View.GONE);
        }
        
        // Like and comment counts
        holder.likeCountTextView.setText(String.valueOf(moment.getLikeCount()));
        holder.commentCountTextView.setText(String.valueOf(moment.getCommentCount()));
        
        // Like status
        if (moment.isLikedByMe()) {
            holder.likeCountTextView.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.ic_liked, 0, 0, 0);
        } else {
            holder.likeCountTextView.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.ic_like, 0, 0, 0);
        }
        
        // Likes section
        if (moment.getLikeCount() > 0) {
            holder.likesLayout.setVisibility(View.VISIBLE);
            
            // Format likes text
            String likesText = formatLikesText(moment.getLikedUsers());
            holder.likesTextView.setText(likesText);
        } else {
            holder.likesLayout.setVisibility(View.GONE);
        }
        
        // Comments section
        if (moment.getCommentCount() > 0) {
            holder.dividerLikesComments.setVisibility(View.VISIBLE);
            setupComments(holder, moment);
        } else {
            holder.dividerLikesComments.setVisibility(View.GONE);
        }
        
        // Show/hide likes and comments container
        if (moment.getLikeCount() > 0 || moment.getCommentCount() > 0) {
            holder.likesCommentsLayout.setVisibility(View.VISIBLE);
        } else {
            holder.likesCommentsLayout.setVisibility(View.GONE);
        }
        
        // Click listeners
        holder.itemView.setOnClickListener(v -> {
            if (momentClickListener != null) {
                momentClickListener.onMomentClick(moment);
            }
        });
        
        holder.likeCountTextView.setOnClickListener(v -> {
            if (likeClickListener != null) {
                likeClickListener.onLikeClick(moment, position);
            }
        });
        
        holder.commentCountTextView.setOnClickListener(v -> {
            if (commentClickListener != null) {
                commentClickListener.onCommentClick(moment, position);
            }
        });
    }

    private void setupImageGrid(MomentViewHolder holder, Moment moment) {
        List<String> images = moment.getImages();
        if (images != null && !images.isEmpty()) {
            holder.imagesRecyclerView.setVisibility(View.VISIBLE);
            
            int spanCount = determineSpanCount(images.size());
            GridLayoutManager layoutManager = new GridLayoutManager(context, spanCount);
            holder.imagesRecyclerView.setLayoutManager(layoutManager);
            
            ImageGridAdapter adapter = new ImageGridAdapter(context, images);
            holder.imagesRecyclerView.setAdapter(adapter);
        } else {
            holder.imagesRecyclerView.setVisibility(View.GONE);
        }
    }

    private int determineSpanCount(int imageCount) {
        if (imageCount == 1) return 1;
        else if (imageCount <= 4) return 2;
        else return 3;
    }

    private void setupComments(MomentViewHolder holder, Moment moment) {
        holder.commentsRecyclerView.setVisibility(View.VISIBLE);
        holder.commentsRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        
        CommentAdapter adapter = new CommentAdapter(context, moment.getComments());
        holder.commentsRecyclerView.setAdapter(adapter);
    }

    private String formatLikesText(List<User> likedUsers) {
        if (likedUsers == null || likedUsers.isEmpty()) {
            return "";
        }
        
        int maxUsersToShow = 3;
        String names = likedUsers.stream()
                .limit(maxUsersToShow)
                .map(User::getName)
                .collect(Collectors.joining(", "));
                
        if (likedUsers.size() > maxUsersToShow) {
            names += "等" + likedUsers.size() + "人觉得很赞";
        }
        
        return names;
    }
    
    private String getTimeAgo(long timestamp) {
        long now = System.currentTimeMillis();
        long diff = now - timestamp;
        
        // Convert to seconds
        long seconds = diff / 1000;
        
        if (seconds < 60) {
            return "刚刚";
        } else if (seconds < 3600) {
            return (seconds / 60) + "分钟前";
        } else if (seconds < 86400) {
            return (seconds / 3600) + "小时前";
        } else {
            return (seconds / 86400) + "天前";
        }
    }

    @Override
    public int getItemCount() {
        return moments.size() + 1; // +1 for header
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? TYPE_HEADER : TYPE_MOMENT;
    }

    static class HeaderViewHolder extends RecyclerView.ViewHolder {
        ImageView coverImageView;
        CircleImageView avatarImageView;
        TextView usernameTextView;

        HeaderViewHolder(View itemView) {
            super(itemView);
            coverImageView = itemView.findViewById(R.id.iv_cover);
            avatarImageView = itemView.findViewById(R.id.iv_avatar);
            usernameTextView = itemView.findViewById(R.id.tv_username);
        }
    }

    static class MomentViewHolder extends RecyclerView.ViewHolder {
        CircleImageView avatarImageView;
        TextView usernameTextView;
        TextView timeTextView;
        ImageButton moreButton;
        TextView contentTextView;
        RecyclerView imagesRecyclerView;
        TextView locationTextView;
        TextView likeCountTextView;
        TextView commentCountTextView;
        LinearLayout likesCommentsLayout;
        LinearLayout likesLayout;
        TextView likesTextView;
        View dividerLikesComments;
        RecyclerView commentsRecyclerView;

        MomentViewHolder(View itemView) {
            super(itemView);
            avatarImageView = itemView.findViewById(R.id.iv_avatar);
            usernameTextView = itemView.findViewById(R.id.tv_username);
            timeTextView = itemView.findViewById(R.id.tv_time);
            moreButton = itemView.findViewById(R.id.btn_more);
            contentTextView = itemView.findViewById(R.id.tv_content);
            imagesRecyclerView = itemView.findViewById(R.id.rv_images);
            locationTextView = itemView.findViewById(R.id.tv_location);
            likeCountTextView = itemView.findViewById(R.id.tv_like_count);
            commentCountTextView = itemView.findViewById(R.id.tv_comment_count);
            likesCommentsLayout = itemView.findViewById(R.id.ll_likes_comments);
            likesLayout = itemView.findViewById(R.id.ll_likes);
            likesTextView = itemView.findViewById(R.id.tv_likes);
            dividerLikesComments = itemView.findViewById(R.id.divider_likes_comments);
            commentsRecyclerView = itemView.findViewById(R.id.rv_comments);
        }
    }
} 